Counting occurrences and frequency of elements in an array and sort them